<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0" />
    <title>html2canvas Complex Example</title>
    <script src="https://cdn.jsdelivr.net/npm/html2canvas@latest/dist/html2canvas.min.js"></script>
    <style>
      #capture {
        padding: 20px;
        background-color: #f5da55;
        border: 1px solid #ccc;
        width: 400px;
        height: 500px;
      }
      #capture h4 {
        color: #000;
      }
      #capture img {
        max-width: 100%;
        height: auto;
      }
      #result {
        width: 400px;
        height: 500px;
      }
    </style>
  </head>
  <body>
    <div id="capture">
      <h4>Hello, world!</h4>
      <p>This is a paragraph inside the capture area.</p>
      <img
        src="avatar.png"
        alt="Sample Image"
        crossorigin="anonymous" />
    </div>

    <button id="captureButton">Capture and Save</button>
    <img
      id="result"
      alt="Captured Image" />

    <script>
      document.getElementById('captureButton').addEventListener('click', function () {
        const captureElement = document.getElementById('capture')
        const resultImage = document.getElementById('result')

        // 设置html2canvas的配置项
        const options = {
          scale: window.devicePixelRatio, // 使用设备像素比来提高图像质量
          useCORS: true, // 允许跨域加载图像
          allowTaint: true, // 允许画布被污染（当使用跨域图像时）
          width: captureElement.offsetWidth, // 设置画布的宽度
          height: captureElement.offsetHeight // 设置画布的高度
        }

        // 使用html2canvas将DOM元素转换为画布
        html2canvas(captureElement, options)
          .then((canvas) => {
            // 将画布转换为base64编码的图像数据
            const imageData = canvas.toDataURL('image/png')

            // 将图像数据设置为resultImage的src属性
            resultImage.src = imageData

            // 可选：自动下载生成的图像
            const downloadLink = document.createElement('a')
            downloadLink.href = imageData
            downloadLink.download = 'captured-image.png'
            document.body.appendChild(downloadLink)
            downloadLink.click()
            document.body.removeChild(downloadLink)
          })
          .catch((error) => {
            console.error('Error capturing the element:', error)
          })
      })
    </script>
  </body>
</html>
